package com.cn.boot.jpa.service.impl;

import com.cn.boot.jpa.common.CommonResult;
import com.cn.boot.jpa.entity.UserEntity;
import com.cn.boot.jpa.repository.UserRepository;
import com.cn.boot.jpa.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户业务逻辑类
 *
 * @author LXJ
 **/
@Service
@CacheConfig(cacheNames = "user")
public class UserService implements IUserService {
    @Autowired
    private UserRepository userRepository;

    /**
     * 查询用户列表
     * 查询数据不分页
     * List<UserEntity> list =userRepository.findAll();
     * 分页:page(页码)，size(一页显示几条)
     * 返回一个PageRequest对象
     * 查询数据分页
     */
    @Cacheable(keyGenerator = "keyGenerator")
    @Override
    public CommonResult findAll(Integer page, Integer size) {
        PageRequest of = PageRequest.of(page, size);
        Page<UserEntity> all = userRepository.findAll(of);
        return CommonResult.success(all);
    }

    /**
     * 模糊查询
     * 根据nickName和email来查询用户
     */
    @Override
    public CommonResult findAllByNickNameAndEmail(String nickName, String email) {
        List<UserEntity> list = userRepository.findAllByNickNameLikeAndEmailLike("%" + nickName + "%", "%" + email + "%");
        return CommonResult.success(list);
    }

    /**
     * 添加用户
     */
    @Caching(
            put = @CachePut(key = "#result.id"),//result等于UserEntity
            evict = @CacheEvict(key = "'findAll[]'")//删除缓存中用户列表的key
    )
    @Override
    public CommonResult addUser(UserEntity userEntity) {
        userEntity.setId(null);
        userRepository.save(userEntity);
        return CommonResult.success(userEntity);

    }

    /**
     * 批量添加
     */
    @Override
    public CommonResult addUsers(List<UserEntity> users) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(null);
        List<UserEntity> all = userRepository.saveAll(users);
        return CommonResult.success(all);
    }

    /**
     * 根据id查找用户
     */
    @Cacheable(key = "#id")
    @Override
    public CommonResult findById(Integer id) {
        UserEntity userEntity = userRepository.findById(id).get();
        return CommonResult.success(userEntity);
    }


}
